//
//  BHServiceEngine.m
//  s.
//
//  Created by fanshijian on 2022/8/23.
//  Copyright © 2022 J. All rights reserved.
//

#import "BHServiceEngine.h"
#import "MBLoadingView.h"
#import "NSURLSessionTask+operation.h"
#import "NSString+YYAdd.h"
#import "JYUrlData.h"
#import <AFNetworking/AFNetworking.h>
@implementation BHServiceEngine


AFHTTPRequestOperation* request_conv(NSString *url_flag ,id parmeters, FinishBlock completeBlock) {
    NSDictionary *info = JYURLInfo(url_flag);
    NSString *url = [info[@"host"] stringByAppendingString:info[@"path"]];
    AFHTTPClientParameterEncoding encode = AFJSONParameterEncoding;
    if ([info[@"encode"] isEqualToString:@"0"]) {
        encode = AFFormURLParameterEncoding;
    }else if ([info[@"encode"] isEqualToString:@"2"]){
        encode = AFPropertyListParameterEncoding;
    }
    NSString *decode = info[@"decode"];
    return request(url, info[@"method"], encode, decode, parmeters, completeBlock);
}

AFHTTPRequestOperation* request(NSString *urlString,
                                NSString *method,
                                AFHTTPClientParameterEncoding parameterEncoding,
                                NSString *decode,
                                id parmeters,
                                FinishBlock completeBlock ) {
    return newrequest(urlString, method,parameterEncoding, decode, parmeters, completeBlock);
}

AFHTTPRequestOperation *newrequest(NSString *urlString,
                                   NSString *method ,
                                   AFHTTPClientParameterEncoding parameterEncoding,
                                   NSString *decode,
                                   id parmeters,
                                   FinishBlock completeBlock) {
#if DEBUG
    NSDate *start = NSDate.new;
#endif
    if (!urlString || urlString.length == 0) {
        if (completeBlock) {
            completeBlock(nil,nil);
        }
        return nil;
    }
    
    NSURL *url = [NSURL URLWithString:urlString];
    if (url == nil) {
        if (completeBlock) {
            completeBlock(nil,nil);
        }
        return nil;
    }
    
    NSLog(@"url : %@  [req] params : %@ ",url,parmeters);
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //    // fansj 如果要抓包，需要去掉SSL证书校验
    //    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    //    manager.securityPolicy.allowInvalidCertificates = YES;
    //    [manager.securityPolicy setValidatesDomainName:NO];
    //    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    //    [securityPolicy setAllowInvalidCertificates:YES];
    //    securityPolicy.validatesDomainName = NO;
    //    [manager setSecurityPolicy:securityPolicy];
    
    if (parameterEncoding == AFJSONParameterEncoding){
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
    }else if (parameterEncoding == AFPropertyListParameterEncoding){
        manager.requestSerializer = [AFPropertyListRequestSerializer serializer];
    }else{
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    }
    
    urlString = url.absoluteString;
#if DEBUG
    manager.requestSerializer.timeoutInterval = 10;
#else
    manager.requestSerializer.timeoutInterval = 20;
#endif
    
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    if (decode) {
        if ([decode isEqualToString:@"1"]) {
            // 图片
            manager.responseSerializer = [AFImageResponseSerializer serializer];
        }
    }
    
    NSMutableSet *acceptableContentTypes = [NSMutableSet setWithSet:manager.responseSerializer.acceptableContentTypes];
    [acceptableContentTypes addObject:@"application/json"];
    [acceptableContentTypes addObject:@"text/html"];
    [acceptableContentTypes addObject:@"text/plain"];
    [acceptableContentTypes addObject:@"application/x-mpegurl"];
    [acceptableContentTypes addObject:@"application/octet-stream"];
    [acceptableContentTypes addObject:@"image/png"];
    [acceptableContentTypes addObject:@"image/jpeg"];
    manager.responseSerializer.acceptableContentTypes = acceptableContentTypes;
    
    // fansj
    id params = parmeters;
    
    __block NSURLSessionDataTask *sessionTask = nil;
    __block FinishBlock cblock = completeBlock;
    
    id successBlock = ^(NSURLSessionDataTask * task, id  responseObject){
#if DEBUG
        if (start) {
            NSLog(@"接口[%@]请求时间 : %f",urlString, [start timeIntervalSinceNow]);
        }
#endif
        [[MBLoadingView shareLoadingView] hideLoadingView];
        NSLog(@"url : %@ [%@] [res] response : %@",url,task.requestId,responseObject);
        if (cblock) {
            cblock(task.operation,responseObject);
            cblock = nil;
        }
        [manager.session finishTasksAndInvalidate];
    };
    
    id failureBlock = ^(NSURLSessionDataTask * task, NSError * error){
        NSLog(@"url : %@ [%@] [res] error : %@",url,task.requestId,error);
        [[MBLoadingView shareLoadingView] hideLoadingView];
        if (error.code == NSURLErrorCancelled) {
            //用户取消，直接上报
            task.operation.error = error;
            task.operation.cancelled = YES;
            if (cblock) {
                cblock(task.operation,nil);
                cblock = nil;
            }
        }else{
            if (task) {
                task.operation.error = error;
                if (cblock) { cblock(task.operation,error); cblock = nil;}
            }else{//task or request is nil
                if (cblock) { cblock(task.operation,error); cblock = nil; }
                // 可以做一些上报操作
            }
        }
        [manager.session finishTasksAndInvalidate];
    };
    
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:method URLString:urlString parameters:nil error:nil];
    
    [request addValue:@"application/json"forHTTPHeaderField:@"Content-Type"];
    
    
    
    NSData *body = [params mj_JSONData];
    [request setHTTPBody:body];
    [[MBLoadingView shareLoadingView] showLoadingView];
//    sessionTask = [manager dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
//        
//    } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
//        
//    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
//        [[MBLoadingView shareLoadingView] hideLoadingView];
//        if (error) {
//            NSLog(@"url : %@ [%@] [res] error : %@",url,sessionTask.requestId,error);
//            if (error.code == NSURLErrorCancelled) {
//                //用户取消，直接上报
//                sessionTask.operation.error = error;
//                sessionTask.operation.cancelled = YES;
//                if (cblock) {
//                    cblock(sessionTask.operation,nil);
//                    cblock = nil;
//                }
//            }else{
//                if (sessionTask) {
//                    sessionTask.operation.error = error;
//                    if (cblock) { cblock(sessionTask.operation,error); cblock = nil;}
//                }else{//task or request is nil
//                    if (cblock) { cblock(sessionTask.operation,error); cblock = nil; }
//                    // 可以做一些上报操作
//                }
//            }
//            [manager.session finishTasksAndInvalidate];
//        } else {
//#if DEBUG
//            if (start) {
//                NSLog(@"接口[%@]请求时间 : %f",urlString, [start timeIntervalSinceNow]);
//            }
//#endif
//            
//            NSLog(@"url : %@ [%@] [res] response : %@",url,sessionTask.requestId,responseObject);
//            if (cblock) {
//                cblock(sessionTask.operation,responseObject);
//                cblock = nil;
//            }
//            [manager.session finishTasksAndInvalidate];            }
//    }];
    
    if ([method isEqualToString:@"POST"]) {
        sessionTask = [manager POST:urlString parameters:params headers:nil progress:nil success:successBlock failure:failureBlock];
    }else if ([method isEqualToString:@"GET"]){
        sessionTask = [manager GET:urlString parameters:parmeters headers:nil progress:nil success:successBlock failure:failureBlock];
    }
    [sessionTask resume];
    sessionTask.operation.requestUrl = url;
    sessionTask.requestId = [FSJUtility fsj_uuid];
    return sessionTask.operation;
}


//AFHTTPRequestOperation* uploadFile_request(NSString *url_flag ,id __nullable parmeters, NSString * suf, FinishBlock completeBlock) {
//    NSDictionary *info = JYURLInfo(url_flag);
//    NSString *urlString = [info[@"host"] stringByAppendingString:info[@"path"]];
//    AFHTTPClientParameterEncoding encode = AFJSONParameterEncoding;
//    if ([info[@"encode"] isEqualToString:@"0"]) {
//        encode = AFFormURLParameterEncoding;
//    }else if ([info[@"encode"] isEqualToString:@"2"]){
//        encode = AFPropertyListParameterEncoding;
//    }
//    NSString *decode = info[@"decode"];
//#if DEBUG
//    NSDate *start = NSDate.new;
//#endif
//    if (!urlString || urlString.length == 0) {
//        if (completeBlock) {
//            completeBlock(nil,nil);
//        }
//        return nil;
//    }
//    
//    NSURL *url = [NSURL URLWithString:urlString];
//    if (url == nil) {
//        if (completeBlock) {
//            completeBlock(nil,nil);
//        }
//        return nil;
//    }
//    
//    NSString *uuid = [FSJUtility fsj_uuid];
//    NSLog(@"url : %@ [%@] [req] params : %@ token : %@",url,uuid,parmeters,UserToken);
//    
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//
////    if (encode == AFJSONParameterEncoding){
////        manager.requestSerializer = [AFJSONRequestSerializer serializer];
////    }else if (encode == AFPropertyListParameterEncoding){
////        manager.requestSerializer = [AFPropertyListRequestSerializer serializer];
////    }else{
//        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
////    }
//    
//    urlString = url.absoluteString;
//#if DEBUG
//    manager.requestSerializer.timeoutInterval = 30;
//#else
//    manager.requestSerializer.timeoutInterval = 20;
//#endif
//    
//    [manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
//    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
// 
//    manager.responseSerializer = [AFJSONResponseSerializer serializer];
//    // 图片
////    manager.responseSerializer = [AFImageResponseSerializer serializer];
//    
//    NSMutableSet *acceptableContentTypes = [NSMutableSet setWithSet:manager.responseSerializer.acceptableContentTypes];
//    [acceptableContentTypes addObject:@"application/json"];
//    [acceptableContentTypes addObject:@"text/html"];
//    [acceptableContentTypes addObject:@"text/plain"];
//    [acceptableContentTypes addObject:@"application/x-mpegurl"];
//    [acceptableContentTypes addObject:@"application/octet-stream"];
//    [acceptableContentTypes addObject:@"image/png"];
//    [acceptableContentTypes addObject:@"image/jpeg"];
//    manager.responseSerializer.acceptableContentTypes = acceptableContentTypes;
//    
//    __block NSURLSessionDataTask *sessionTask = nil;
//    __block FinishBlock cblock = completeBlock;
//    
////    if (UserToken) {
////        [manager.requestSerializer setValue:@"Asia/Yangon" forHTTPHeaderField:@"X-Time-Zone"];
////        [manager.requestSerializer setValue:[UserDefaults fetchLanguage] forHTTPHeaderField:@"Content-Language"];
////        [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@", UserToken] forHTTPHeaderField:@"Authorization"];
////        
////    } else {
//        NSString * timestamp = [MBDateManager shortStringFromDate:[NSDate date]];
//        [manager.requestSerializer setValue:timestamp forHTTPHeaderField:@"timestamp"];
//        
//        char ch[8];
//        for (int index=0; index<8; index++) {
//            int num = arc4random_uniform(75)+48;
//            if (num>57 && num<65) { num = num%57+48; }
//            else if (num>90 && num<97) { num = num%90+65; }
//            ch[index] = num;
//        }
//        
//        NSString *nonce = [[NSString alloc] initWithBytes:ch length:8 encoding:NSUTF8StringEncoding];
//        [manager.requestSerializer setValue:nonce forHTTPHeaderField:@"nonce"];
//        
//        NSString * secret = @"Dq0+2TeKiieDJKpqMPGF6YQrjvrDandzoOcB7u2CqkmsWCbLaAVdfOVbB5P50UMc";
//        NSString * signStr = [NSString stringWithFormat:@"%@%@%@",timestamp,nonce, secret];
//        NSString * sign = [signStr md5String].uppercaseString;
//        
//        [manager.requestSerializer setValue:sign forHTTPHeaderField:@"sign"];
//        [manager.requestSerializer setValue:@"Asia/Yangon" forHTTPHeaderField:@"X-Time-Zone"];
//        [manager.requestSerializer setValue:[UserDefaults fetchLanguage] forHTTPHeaderField:@"Content-Language"];
////    }
//    [[MBLoadingView shareLoadingView] showLoadingView];
//    sessionTask = [manager POST:urlString parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//        NSData *data= parmeters;
//        // 设置时间格式
//        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//        formatter.dateFormat = @"yyyyMMddHHmmss";
//        formatter.locale =  [NSLocale systemLocale];
//        formatter.calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierISO8601];
//        NSString *str = [formatter stringFromDate:[NSDate date]];
//        NSString *fileName = suf;
//        if ([suf isEqualToString:@"png"]) {
//            fileName = [NSString stringWithFormat:@"%@.%@", str, suf];
//        }
//        fileName = [NSString stringWithFormat:@"%@.%@", str, [[suf componentsSeparatedByString:@"."].lastObject lowercaseString]];
//        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"application/octet-stream"];
//        } progress:^(NSProgress * _Nonnull uploadProgress) {
//            
//        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            [[MBLoadingView shareLoadingView] hideLoadingView];
//#if DEBUG
//            if (start) {
//                NSLog(@"接口[%@]请求时间 : %f",urlString, [start timeIntervalSinceNow]);
//            }
//#endif
//            
//            NSLog(@"url : %@ [%@] [res] response : %@",url,sessionTask.requestId,responseObject);
//            if (cblock) {
//                cblock(sessionTask.operation,responseObject);
//                cblock = nil;
//            }
//            [manager.session finishTasksAndInvalidate];
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            NSLog(@"url : %@ [%@] [res] error : %@",url,sessionTask.requestId,error);
//            [[MBLoadingView shareLoadingView] hideLoadingView];
//            if (error.code == NSURLErrorCancelled) {
//                //用户取消，直接上报
//                sessionTask.operation.error = error;
//                sessionTask.operation.cancelled = YES;
//                if (cblock) {
//                    cblock(sessionTask.operation,nil);
//                    cblock = nil;
//                }
//            }else{
//                if (sessionTask) {
//                    sessionTask.operation.error = error;
//                    if (cblock) { cblock(sessionTask.operation,error); cblock = nil;}
//                }else{//task or request is nil
//                    if (cblock) { cblock(sessionTask.operation,error); cblock = nil; }
//                    // 可以做一些上报操作
//                }
//            }
//            [manager.session finishTasksAndInvalidate];
//        }];
//  
//    [sessionTask resume];
//    sessionTask.operation.requestUrl = url;
//    sessionTask.requestId = uuid;
//    return sessionTask.operation;
//}

@end
